<template>
  <div class="user-list">
    <h2>用户列表</h2>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="dialogVisible = true">新增用户</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" class="user-table" border>
        <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip  />
        <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip />
        <el-table-column prop="nickname" label="昵称" width="100" show-overflow-tooltip />
        <el-table-column prop="followerCount" label="粉丝数" width="80">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.followerCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="followingCount" label="关注数" width="80">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.followingCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="beanBalance" label="阅豆" width="80">
          <template #default="scope">
            <el-tag type="warning">{{ scope.row.beanBalance || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="avatarUrl" label="头像" width="100">
          <template #default="scope">
            <el-avatar v-if="scope.row.avatarUrl" :size="40" :src="scope.row.avatarUrl" />
            <el-avatar v-else :size="40" :icon="UserFilled" />
          </template>
        </el-table-column>
        <el-table-column prop="bio" label="简介" width="100" show-overflow-tooltip />
        <el-table-column prop="wechatQrcodeUrl" label="微信二维码" width="100" show-overflow-tooltip />
        <el-table-column prop="wechatOpenid" label="微信openid" width="100" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <!-- 0 禁用 1 正常 2待审核 -->
            <el-tag :type="scope.row.status === 0 ? 'danger' : (scope.row.status === 1 ? 'success' : 'info')">
              {{ scope.row.status === 0 ? '禁用' : (scope.row.status === 1 ? '正常' : '待审核') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="100" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
            <el-button
              size="small"
              :type="isCurrentUser(scope.row.id) ? 'info' : 'primary'"
              :disabled="isCurrentUser(scope.row.id)"
              @click="handleFollow(scope.row.id)"
            >{{ isCurrentUser(scope.row.id) ? '自己' : '关注' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>

    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增用户"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwordHash">
          <el-input v-model="userForm.passwordHash" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="阅豆" prop="beanBalance">
          <el-input v-model="userForm.beanBalance" placeholder="请输入阅豆余额"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="userForm.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input v-model="userForm.bio" type="textarea" placeholder="请输入个人简介"></el-input>
        </el-form-item>
        <el-form-item label="微信二维码" prop="wechatQrcodeUrl">
          <el-input v-model="userForm.wechatQrcodeUrl" placeholder="请输入微信二维码URL"></el-input>
        </el-form-item>
        <el-form-item label="微信OpenID" prop="wechatOpenid">
          <el-input v-model="userForm.wechatOpenid" placeholder="请输入微信OpenID"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option :value="0" label="禁用"></el-option>
            <el-option :value="1" label="正常"></el-option>
            <el-option :value="2" label="待审核"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { queryPageApi, addApi, updateApi, deleteBatchApi } from '../api/user'
import { followUserApi } from '../api/follow'
import { useUserStore } from '../store/user'

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const tableData = ref([])
const dialogVisible = ref(false)
const userFormRef = ref(null)

// 列显示控制
const columnOptions = reactive([
  { prop: 'id', label: 'ID', visible: true },
  { prop: 'username', label: '用户名', visible: true },
  { prop: 'nickname', label: '昵称', visible: true },
  { prop: 'followerCount', label: '关注数', visible: true },
  { prop: 'followingCount', label: '粉丝数', visible: true },
  { prop: 'beanBalance', label: '阅豆', visible: true },
  { prop: 'avatarUrl', label: '头像', visible: true },
  { prop: 'bio', label: '简介', visible: false },
  { prop: 'wechatQrcodeUrl', label: '微信二维码', visible: false },
  { prop: 'wechatOpenid', label: '微信openid', visible: false },
  { prop: 'status', label: '状态', visible: true },
  { prop: 'createTime', label: '创建时间', visible: true },
  { prop: 'updateTime', label: '更新时间', visible: true },
  { prop: 'actions', label: '操作', visible: true }
])



// 处理列显示/隐藏
const handleColumnVisibility = (command) => {
  // 防止点击checkbox时触发dropdown-item的command事件
  // 实际上在checkbox的@click.stop已经阻止了冒泡
  // 这里只是一个额外的保护措施
}

// 用户表单数据
const userForm = reactive({
  id:"",
  username: '',
  passwordHash: '',
  nickname: '',
  followerCount: 0,
  followingCount: 0,
  beanBalance: '0.00',
  avatarUrl: '',
  bio: '',
  wechatQrcodeUrl: '',
  wechatOpenid: '',
  status: 1,
  createTime: '2025-06-30T12:00:00',
  updateTime: '2025-06-30T12:00:00'
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 生命周期  组件加载完成时调用
onMounted(async () => {
    renderList()
})

// 渲染列表
const renderList = () => {
  queryPageApi({
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    tableData.value = res.data.rows
    total.value = res.data.total
  })
}

// 提交表单
const submitForm = () => {
  // 如果有Id 则是修改 没有则是新增
  if(userForm.id){
    updateApi(userForm)
        .then(res => {
          ElMessage({
            message: '修改用户成功',
            type: 'success'
          })
          console.log(res.data)
          // 关闭对话框
          dialogVisible.value = false
          // 重置表单
          resetForm()
          // 刷新列表
          renderList()
        })
        .catch(err => {
          ElMessage({
            message: '修改用户失败: ' + (err.response?.data?.message || err.message),
            type: 'error'
          })
        })
  }else{
    userFormRef.value.validate((valid) => {
    if (valid) {
      // 发送请求创建用户
      addApi(userForm)
        .then(res => {
          ElMessage({
            message: '添加用户成功',
            type: 'success'
          })
          // 关闭对话框
          dialogVisible.value = false
          // 重置表单
          resetForm()
          // 刷新列表
          renderList()
        })
        .catch(err => {
          ElMessage({
            message: '添加用户失败: ' + (err.response?.data?.message || err.message),
            type: 'error'
          })
        })
    } else {
      return false
    }
  })
  }
}
// 重置表单
const resetForm = () => {
  userFormRef.value.resetFields()
  Object.assign(userForm, {
    id:'',
    username: '',
    passwordHash: '',
    nickname: '',
    followerCount: 0,
    followingCount: 0,
    beanBalance: '0.00',
    avatarUrl: '',
    bio: '',
    wechatQrcodeUrl: '',
    wechatOpenid: '',
    status: 1
  })
}

const handleEdit = (row) => {
  dialogVisible.value = true
  //深拷贝的作用 ： 避免直接修改原对象，影响其他地方的使用
  Object.assign(userForm, row)
  //如果有Id 就是修改 否则是新增
  if(userForm.id){
    userForm.createTime = new Date(userForm.createTime).toISOString()
    userForm.updateTime = new Date(userForm.updateTime).toISOString()
  }else{
    resetForm()
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteBatchApi([id])
        ElMessage.success('删除成功')
        renderList()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 获取用户存储
const userStore = useUserStore()

// 检查是否是当前登录用户
const isCurrentUser = (userId) => {
  const currentUser = userStore.userInfo
  return currentUser && currentUser.id === userId
}

// 关注用户
const handleFollow = async (id) => {
  // 如果是当前用户，不允许关注自己
  if (isCurrentUser(id)) {
    ElMessage.warning('不能关注自己')
    return
  }
  
  try {
    const response = await followUserApi(id)
    ElMessage.success(response.data || '关注成功')
    
    // 更新当前用户信息（如果需要获取最新的用户信息，可以添加获取当前用户信息的API调用）
    // 这里我们简单地刷新整个列表以获取最新数据
    renderList()
    
    // 显示关注奖励提示
    ElMessage({
      message: '恭喜您获得10阅豆奖励！',
      type: 'success',
      duration: 3000
    })
  } catch (error) {
    console.error('关注失败:', error)
    if (error.response?.data?.message?.includes('重复关注')) {
      ElMessage.warning('您已经关注过该用户')
    } else {
      ElMessage.error(error.response?.data?.message || '关注失败')
    }
  }
}
</script>

<style scoped lang="less">
.user-list {
  h2 {
    margin-bottom: 20px;
    color: #303133;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>

<style>
/* 全局表格单元格样式 */
.user-table .el-table__cell .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>